import {
  AuditMaterialApi,
  queryMaterialAuditLog,
  updateMaterialStatus,
} from '@/api/audit/content/material'
import { UpdateMaterialStatusReq } from '@/api/audit/content/model/materialModel'
import {
  MaterialItem,
  MaterialStatus,
} from '@/components/ItemList/MaterialList/types'
import { computed, reactive } from '@vue/runtime-core'
import { message } from 'ant-design-vue'
import { useStore } from '@/store'
import { AuditMaterialDialogState } from '../types'

const useAuditMaterialDialog = (
  searchApi: AsyncFun,
  asyncToPaixin: (accessList: MaterialItem[]) => Promise<void>
) => {
  const store = useStore()
  const auditMaterialDialogState = reactive<AuditMaterialDialogState>({
    visiable: false,
    auditLogs: [],
    currentItem: undefined,
    formData: {
      status: MaterialStatus.CHECK_PENDING,
      memo: '',
    },
    statusList: [
      {
        label: '审核通过',
        value: MaterialStatus.NORMAL,
        title: '审核通过',
      },
      {
        label: '审核不通过',
        value: MaterialStatus.REJECT,
        title: '审核不通过',
      },
    ],
  })

  const openAuditMaterialDialog = async (item: MaterialItem) => {
    auditMaterialDialogState.currentItem = item
    auditMaterialDialogState.formData.status = item.status
    auditMaterialDialogState.formData.memo = ''

    const { data } = await queryMaterialAuditLog(item.id)
    auditMaterialDialogState.auditLogs = data

    auditMaterialDialogState.visiable = true
  }
  const queryMaterialAuditLogLoading = computed(() =>
    store.getters['global/isOpLoading'](
      AuditMaterialApi.QUERY_MATERIAL_AUDIT_LOG
    )
  )

  const comfirmMaterialAudit = async () => {
    if (auditMaterialDialogState.currentItem) {
      const reqData: UpdateMaterialStatusReq = {
        id: auditMaterialDialogState.currentItem.id,
        ...auditMaterialDialogState.formData,
      }
      await updateMaterialStatus(reqData)
      message.success('审核成功')
      if (auditMaterialDialogState.formData.status === MaterialStatus.NORMAL) {
        await asyncToPaixin([auditMaterialDialogState.currentItem])
      }
      auditMaterialDialogState.visiable = false
      await searchApi()
    }
  }
  const updateMaterialStatusLoading = computed(() =>
    store.getters['global/isOpLoading'](AuditMaterialApi.UPDATE_MATERIAL_STATUS)
  )

  return {
    auditMaterialDialogState,
    openAuditMaterialDialog,
    comfirmMaterialAudit,
    updateMaterialStatusLoading,
    queryMaterialAuditLogLoading,
  }
}

export default useAuditMaterialDialog
